<template>
  <div class="club-member-management">
    <!-- 搜索和添加成员区域 -->
    <div class="action-bar">
      <!-- 搜索框 -->
      <div class="search-container">
        <el-input
          v-model="clubMemberQueryRequest.userName"
          placeholder="输入用户名搜索"
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button @click="handleSearch" type="primary">搜索</el-button>
      </div>

      <!-- 添加成员按钮 -->
      <el-button type="primary" @click="handleAddMember">添加成员</el-button>
    </div>

    <!-- 成员列表 -->
    <el-table
      :data="paginatedMemberList"
      class="member-table"
      style="width: 100%"
    >
      <el-table-column prop="userId" label="用户编号" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="role" label="身份">
        <template #default="scope">
          <el-tag :type="scope.row.role === '社长' ? 'danger' : 'success'">
            {{ scope.row.role }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="grade" label="年级" />
      <el-table-column prop="major" label="专业" />
      <el-table-column prop="class" label="班级" />
      <el-table-column prop="contact" label="联系方式" />
      <el-table-column label="操作" v-if="showRemoveButton">
        <template #default="scope">
          <el-button
            v-if="scope.row.role !== '社长'"
            size="small"
            type="danger"
            @click="handleRemoveMember(scope.row)"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="clubMemberQueryRequest.current"
        :page-size="clubMemberQueryRequest.pageSize"
        :total="totalItems"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
      />
    </div>
  </div>

  <el-dialog
      v-model="dialogVisible"
      title="确认移除"
      width="30%"
      :before-close="handleClose"
  >
    <span>是否将此成员移出社团？</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">否</el-button>
        <el-button type="primary" @click="confirmRemoveMember">
          是
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { useUserStore } from "../../../stores/user.ts";
import {
  AdminClubControllerService,
  ClubControllerService,
  type ClubMemberQueryRequest, type ClubMembershipDeleteRequest,
  type ClubMembershipVO,
} from "../../../../generated";

// 定义成员数据结构
interface Member {
  userId: number;
  username: string;
  role: string;
  grade: string;
  major: string;
  class: string;
  contact: string;
}

const store = useUserStore();
const memberList = ref<Member[]>([]);
const totalItems = ref(0);
const clubMemberQueryRequest = ref<ClubMemberQueryRequest>({
  pageSize: 10,
  current: 1,
  clubId: store.managedClubId,
  userName: "",
});

const loadData = async () => {
  const res = await ClubControllerService.listUserVoInClubByPage(
    clubMemberQueryRequest.value,
  );
  if (res.code === 0) {
    const userVoList = res.data?.records as ClubMembershipVO[];
    memberList.value = userVoList.map(
      (memberShipVO) =>
        ({
          userId: memberShipVO.userVO?.id,
          username: memberShipVO.userVO?.userName,
          role: memberShipVO.identity === "member" ? "成员" : "社长",
          grade: memberShipVO.userVO?.grade,
          class: memberShipVO.userVO?.userClass,
          contact: memberShipVO.userVO?.phoneNumber,
        }) as Member,
    );
    totalItems.value = userVoList.length;
  } else {
    ElMessage.error("加载数据失败：" + res.message);
  }
};

const paginatedMemberList = computed(() => {
  const start =
    ((clubMemberQueryRequest.value.current as number) - 1) *
    (clubMemberQueryRequest.value.pageSize as number);
  const end = start + (clubMemberQueryRequest.value.pageSize as number);
  return memberList.value.slice(start, end);
});

onMounted(() => {
  loadData();
});

const handleSearch = () => {
  clubMemberQueryRequest.value.current = 1;
  loadData();
};

// 页码改变处理
const handlePageChange = (page: number) => {
  clubMemberQueryRequest.value.current = page;
  loadData();
};

// 计算属性：是否显示移除按钮（至少有一个非社长成员时显示）
const showRemoveButton = computed(() => {
  return memberList.value.some((member) => member.role !== "社长");
});

// 添加成员方法
const handleAddMember = () => {
  window.open("/manager/member/add", "_blank");
};

const dialogVisible = ref(false);
const deleteUserId = ref(0);

const handleRemoveMember = (member: Member) => {
  deleteUserId.value = member.userId;
  dialogVisible.value = true;
};

// 添加确认移除成员的函数
const confirmRemoveMember = async () => {
    try {
      const request = {
        userId: deleteUserId.value,
        clubId: store.managedClubId,
      } as ClubMembershipDeleteRequest;
      const res = await AdminClubControllerService.deleteMemberFromClub(request);

      if (res.code === 0) {
        ElMessage.success("成员已成功移除");
        // 重新加载数据
        await loadData();
      } else {
        ElMessage.error("移除成员失败：" + res.message);
      }
    } catch (error) {
      ElMessage.error("移除成员时发生错误");
    } finally {
      dialogVisible.value = false;
    }

};

// 添加关闭对话框的处理函数
const handleClose = (done: () => void) => {
  ElMessageBox.confirm("确认关闭？")
      .then(() => {
        done();})
      .catch(() => {
        // 取消关闭
      });
};
</script>

<style scoped>
.club-member-management {
  padding: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  align-items: center;
}

.search-input {
  width: 300px;
}

.search-input {
  width: 300px;
  margin-right: 10px;
}

.club-member-management {
  padding: 20px;
  width: 100%; /* 确保管理区域占满父容器宽度 */
}

.member-table {
  width: 100%;
  table-layout: fixed; /* 使用固定表格布局 */
}

.member-table ::v-deep(.el-table__inner-wrapper) {
  width: 100%; /* 确保内部包装器也是 100% 宽度 */
}

.member-table ::v-deep(.el-table__header),
.member-table ::v-deep(.el-table__body) {
  width: 100% !important; /* 强制表头和表体宽度为 100% */
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
